package com.kuang.servlet.user;

import com.alibaba.fastjson.JSONArray;
import com.kuang.pojo.Role;
import com.kuang.pojo.User;
import com.kuang.service.role.RoleServiceImpl;
import com.kuang.service.user.UserService;
import com.kuang.service.user.UserServiceImpl;
import com.kuang.util.Constants;
import com.kuang.util.PageSupport;
import com.mysql.jdbc.StringUtils;
import org.junit.Test;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


//实现servlet复用
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if ("savepwd".equals(method) && method != null) {
            this.updatePwd(req, resp);
        } else if ("pwdmodify".equals(method) && method != null) {
            this.pwdModify(req, resp);
        } else if ("query".equals(method) && method != null) {
            this.userQuery(req, resp);
        } else if ("add".equals(method) && method != null) {
            this.add(req, resp);
        } else if ("ucexist".equals(method) && method != null) {
            this.userCodeExist(req, resp);
        } else if ("modifyexe".equals(method) && method != null) {
            this.userModify(req, resp);
        } else if ("getrolelist".equals(method) && method != null) {
            this.getRoleList(req, resp);
        } else if ("view".equals(method) && method != null) {
            this.getUserById(req, resp, "userview.jsp");
        } else if ("modify".equals(method) && method != null) {
            this.getUserById(req, resp, "usermodify.jsp");
        } else if ("modify".equals(method) && method != null) {
            this.getUserById(req, resp, "usermodify.jsp");
        } else if ("deluser".equals(method) && method != null) {
            this.deleteUser(req,resp);
        }
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    //    修改密码
    public void updatePwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //        从Session里面拿ID
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        String newpassword = req.getParameter("newpassword");

        System.out.println("UserServlet" + newpassword);


        boolean flag = false;

        if (o != null && !StringUtils.isNullOrEmpty(newpassword)) {
            UserService userService = new UserServiceImpl();
            flag = userService.updatePwd(((User) o).getId(), newpassword);
            if (flag) {

                req.setAttribute("message", "修改密码成功，请退出使用新密码密码登录");
//                密码修出成功删除session
                req.getSession().removeAttribute(Constants.USER_SESSION);
            } else {
                req.setAttribute("message", "修改密码失败");
            }

        } else {
            req.setAttribute("message", "新密码有问题");
        }
        req.getRequestDispatcher("pwdmodify.jsp").forward(req, resp);

    }

    //    验证旧密码
    public void pwdModify(HttpServletRequest req, HttpServletResponse resp) {
        //        从Session里面拿ID
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        String oldpassword = req.getParameter("oldpassword");

//        万能map
        HashMap<String, String> resultMap = new HashMap<String, String>();
        if (o == null) {//Session过期
            resultMap.put("result", "sessionerror");
        } else if (StringUtils.isNullOrEmpty(oldpassword)) {//输入密码为空
            resultMap.put("result", "error");
        } else {
            String getUserPassword = ((User) o).getUserPassword();//Session中的用户密码
            if (oldpassword.equals(getUserPassword)) {
                resultMap.put("result", "true");
            } else {
                resultMap.put("result", "false");
            }
        }

        try {
            resp.setContentType("application/json");

            PrintWriter writer = resp.getWriter();
//            JSONArray阿里巴巴的json工具类,转换格式
            writer.write(JSONArray.toJSONString(resultMap));

            writer.flush();
            writer.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    /**
     * @description: 对用户进行查询【重点和难点】
     * @date 20/12/2 19:42
     * @Param: [req, resp]
     * @Return: void
     * 1.获取用户前端的数据（查询）
     * 2.判断请求是否需要执行，看参数的值判断
     * 3.为了实现分页，需要计算出当前页面和总页面，页面大小…
     * 4.用户列表展示
     * 5.返回前端
     */
    private void userQuery(HttpServletRequest req, HttpServletResponse resp) {

        //查询用户列表
        String queryUserName = req.getParameter("queryname");
        String temp = req.getParameter("queryUserRole");
        String pageIndex = req.getParameter("pageIndex");
        System.out.println("测试的" + temp + queryUserName + pageIndex);

        int queryUserRole = 0;

//        获取用户列表
        UserServiceImpl userService = new UserServiceImpl();
        System.out.println(userService);

//        第一次走这个请求一定是第一页，页面大小固定
        int pageSize = 5;
        int currentPageNo = 1;

        if (queryUserName == null) {
            queryUserName = "";
        }

        if (temp != null && !temp.equals("")) {
            queryUserRole = Integer.parseInt(temp);//给查询赋值0，1 ，2 ，3
        }

        if (pageIndex != null) {

            currentPageNo = Integer.parseInt(pageIndex);
        }
//        获取用户总数 (分页 上一页和下一页)
        int totalCount = userService.getUserCount(queryUserName, queryUserRole);
        List<User> userList = null;

        PageSupport pageSupport = new PageSupport();
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(totalCount);

        int totalPageCount = ((int) (totalCount / pageSize)) + 1;
//        控制首页和尾页 如果页面小于一就显示第一页内容


        if (totalPageCount < 1) {
            currentPageNo = 1;
        } else if (currentPageNo > totalPageCount) {//当前页面大于最后一页
            currentPageNo = totalPageCount;
        }
//        获取用户列表展示
        userList = userService.getUserList(queryUserName, queryUserRole, currentPageNo, pageSize);
        req.setAttribute("userList", userList);
//          获取角色列表
        RoleServiceImpl roleServiceImpl = new RoleServiceImpl();
        List<Role> roleList = roleServiceImpl.getRoleList();

        req.setAttribute("roleList", roleList);
        req.setAttribute("totalCount", totalCount);
        req.setAttribute("currentPageNo", currentPageNo);
        req.setAttribute("totalPageCount", totalPageCount);
        req.setAttribute("queryUserName", queryUserName);
        req.setAttribute("queryUserRole", queryUserRole);
//        返回前端
        try {
            req.getRequestDispatcher("userlist.jsp").forward(req, resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    private void add(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        //获取输入的用户参数
        String userCode = req.getParameter("userCode");
        String userName = req.getParameter("userName");
        String userPassword = req.getParameter("userPassword");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");

        //创建一个User对象，并且根据表单获取的内容设置其属性值
        User user = new User();
        user.setUserCode(userCode);
        user.setUserName(userName);
        user.setUserPassword(userPassword);
        user.setAddress(address);
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setGender(Integer.valueOf(gender));
        user.setPhone(phone);
        user.setUserRole(Integer.valueOf(userRole));
        user.setCreationDate(new Date());
        user.setCreatedBy(((User) req.getSession().getAttribute(Constants.USER_SESSION)).getId());

        //调用Service层的方法
        UserService userService = new UserServiceImpl();
        if (userService.add(user)) {
            resp.sendRedirect(req.getContextPath() + "/jsp/user.do?method=query");
        } else {
            req.getRequestDispatcher("useradd.jsp").forward(req, resp);
        }
    }

    /**
     * @description: 判断添加用户的userCode是否可用（是否已经被占用了）
     * @date 20/12/7 20:10
     * @Param: [req, resp]
     * @Return: void
     */
    private void userCodeExist(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        //首先我们判断数据库中是否存在该用户usercode，首先得获取到用户输入的userCode
        String userCode = req.getParameter("userCode");
        //万能的Map：结果集
        Map<String, String> map = new HashMap<String, String>();
        //判断输入是否为空
        if (StringUtils.isNullOrEmpty(userCode)) {
            map.put("userCode", "empty");
        } else {
            UserServiceImpl userService = new UserServiceImpl();
            User user = userService.selectUserCodeExist(userCode);
            if (user != null) {
                map.put("userCode", "exist");
            } else {
                map.put("userCode", "notexist");
            }
        }
        //将Map数据转换成json返回
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
        writer.write(JSONArray.toJSONString(map));
        writer.flush();
        writer.close();
    }

    public void userModify(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
//        接受内容
        String id = req.getParameter("uid");
        String userName = req.getParameter("userName");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");
//        把这些东西存user
        User user = new User();
        user.setId(Integer.valueOf(id));
        user.setUserName(userName);
        user.setAddress(address);
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setGender(Integer.valueOf(gender));
        user.setPhone(phone);
        user.setUserRole(Integer.valueOf(userRole));
        user.setModifyBy(((User) req.getSession().getAttribute(Constants.USER_SESSION)).getId());
        user.setModifyDate(new Date());

        UserServiceImpl userService = new UserServiceImpl();
        boolean b = userService.userModify(user);
        System.out.println(b);
        if (b) {
            resp.sendRedirect(req.getContextPath() + "/jsp/user.do?method=query");
        } else {

            req.getRequestDispatcher("usermodify.jsp").forward(req, resp);

        }
    }


    /**
     * @description: 返回用户角色列表
     * @date 20/12/7 20:04
     * @Param: [req, resp]
     * @Return: void
     */
    private void getRoleList(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        List<Role> roleList = null;
        RoleServiceImpl roleService = new RoleServiceImpl();
        roleList = roleService.getRoleList();
        //把roleList转换成json对象返回
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
        writer.write(JSONArray.toJSONString(roleList));
        writer.flush();
        writer.close();
    }
    /**
     * @description: 通过Id获取用户，查看具体的某一个用户
     * @date 20/12/7 20:56
     * @Param: [request, response, url]
     * @Return: void
     */
    private void getUserById(HttpServletRequest req, HttpServletResponse resp, String url) throws ServletException, IOException {
        //获取传入的id
        String uid = req.getParameter("uid");
        if (!StringUtils.isNullOrEmpty(uid)) {
            UserServiceImpl userService = new UserServiceImpl();
            User userById = userService.getUserById(uid);
            req.setAttribute("user", userById);
            req.getRequestDispatcher(url).forward(req, resp);
        }
    }

    private void deleteUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("uid");
        Integer deleteId=0;

        try {
            deleteId = Integer.parseInt(id);
        } catch (Exception e) {
            deleteId = 0;
        }

//        获取Session里面登录id
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
//        获取用户id
        Integer sessionId = ((User) o).getId();
        System.out.println("接受目标id"+deleteId);
        System.out.println("接受登录用户id"+sessionId);
        HashMap<String, String> map = new HashMap<String, String>();
        if (deleteId <= 0) {
            map.put("delResult", "notexist");
        } else if (sessionId.equals(deleteId)) {
            //判断要删除的id是否等于当前登录用户的id。
            map.put("delResult", "cannotdel");
        } else {
            UserServiceImpl userService = new UserServiceImpl();
            boolean b = false;
            try {
                b = userService.deleteUserById(deleteId);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (b) {
                map.put("delResult", "true");
            } else {
                map.put("delResult", "false");
            }
        }
        //把map转换成json对象输出
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
        writer.write(JSONArray.toJSONString(map));
        writer.flush();
        writer.close();
    }

}


